import postRequest from "../../utils/postRequest";
import request from "../../utils/request";
// 获取全局实例
const appInstance = getApp();
//启动数据库
const DB = wx.cloud.database()
const collectDB = DB.collection('collect')

let startY = 0; // 手指起始的坐标
let moveY = 0; // 手指移动的坐标
let moveDistance = 0; // 手指移动的距离
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coverTransform:'translateY(0)',   //控制元素的transform属性
    coveTransition:'',
    userInfo:{},
    offset:0,
    userstate:false,
    userRecentPlayList:[],
    isMoveToUp:false,
    itemIndex:1,                     //控制选项显示
    globList:[],                      //获取全局音乐播放列表
    index: 0,              // 点击音乐的下标,
    musicList:[],          //歌单列表
    src:'',
    songlists:[],           //数据库收藏歌单
    likemusics:[],
    likemvs:[]
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = wx.getStorageSync('userInfo');
    if(userInfo){ // 用户登录
      // 更新userInfo的状态
      this.setData({
        userInfo: JSON.parse(userInfo),
        userstate:true
      })
    }
    //id 存在时发送用户记录请求
    if(this.data.userInfo.userId){
      this.userRecentPlayList(this.data.userInfo.userId);}
    
          // 订阅来自songDetail页面发布的消息
    // PubSub.subscribe(this.data.type, (msg, type) => {
    //   let {index} = this.data;
    //    index = appInstance.globalData.currentIndex;
    //   // if(type === 'pre'){ // 上一首
    //   //   (index === 0) && (index = recommendList.length);
    //   //   index -= 1;
    //   // }else { // 下一首
    //   //   (index === recommendList.length - 1) && (index = -1);
    //   //   index += 1;
    //   // }
      
    //   // 更新下标
    //   this.setData({
    //     index
    //   })
    //   // console.log(userRecentPlayList[index].song.id)
      
    //   let musicId = appInstance.globalData.playList[index].id;
    //   // 将musicId回传给songDetail页面
    //   PubSub.publish('musicId', musicId)
      
    // });
     //获取用户歌单
    // this.getUsermusicList(this.data.userInfo.userId)
    if(wx.getStorageSync('userInfo')){
      this.getDBsonglists()
    }
    if(wx.getStorageSync('src')){
      let src = wx.getStorageSync('src')
      this.setData({
        src
      })
    }
  },
 
  handleRefresher(){
    // console.log('scroll-view 下拉刷新');
    // 再次发请求，获取最新的视频列表数据
    // console.log('滑到顶了，开始加载更多');

    var that = this;                     //setTimeout里会用到，
    that.setData({                       //MoveToUp触发
      // istrue:false,
      isMoveToUp: true,
    })
    setTimeout(function() {              //时间限制
    that.getDBsonglists()
    console.log("调用成功")
    that.setData({                       //MoveToUp触发
      // istrue:false,
      isMoveToUp: false,
    })
    wx.showToast({
      title: '刷新成功',
      icon:'success',
      duration:1000
    })
    }, 500)     
  },

  getDBsonglists(){
    let songlists = []
    let likemusics = []
    let likemvs = []
    let that = this
     collectDB.where({userId:this.data.userInfo.userId}).get({
      success(res){
        // console.log(res.data[0].songlists)
        songlists = res.data[0].songlists
        likemusics = res.data[0].likemusics
        likemvs = res.data[0].likemvs
        that.setData({
          songlists,
          likemusics,
          likemvs
        })
      }
    })

  }, 

  selectitem(event){

    // console.log(event)
    let {itemIndex} = this.data
    itemIndex = event.currentTarget.dataset.itemindex
    let length = 0
    if(itemIndex==1){
      length  = this.data.likemusics.length
    }else if(itemIndex==2){
      length  = this.data.likemvs.length
    }else{
     length  = this.data.songlists.length
    }

    if(!length){
      let tit = ''
      if(wx.getStorageSync('userInfo')){
        tit='没有数据!'
      }else{
        tit='请先登陆!'
      }
      wx.showToast({
        title:tit,
        icon:'error',
        duration:1000
      })
    }
    this.setData({
      itemIndex
    })
  },


  async getUsermusicList(uid){
    let res = await request('/user/playlist',{uid})
    // console.log(res)
    let musicList = res.playlist
    this.setData({
      musicList
    })
  },
  toMvPlay(event){
   //  console.log(event.currentTarget.dataset.song.id)
   let vid = event.currentTarget.dataset.id
   wx.navigateTo({
     url: '/pages/songPackage/pages/mvplay/mvplay?vid='+vid
   })
 },
 
 tolists(event){
  //  console.log(event.currentTarget.dataset.song.id)
  let listid = event.currentTarget.dataset.id
  wx.navigateTo({
    url: '/pages/songPackage/pages/playListDetail/playListDetail?listid='+listid
  })
},

  text(){
   wx.navigateTo({
     url: '/pages/text/text',
   })
  },
  
 async backUser(){
    var self = this
    wx.showModal({
      title: '提示',
      content: '是否退出账户?',
      success (res) {
        if (res.confirm) {
          if(wx.getStorageSync('src')){wx.removeStorageSync('src')}
          wx.removeStorageSync('userInfo')
          self.setData({
            coverTransform:'translateY(0)',   
            coveTransition:'',
            userInfo:{},
            likemusics:[],
            likemvs:[],
            songlists:[],
            userstate:false,
          })
          wx.navigateTo({
            url: '../login/login',
          })

        } else if (res.cancel) {
         return
        }
      }
    })
  //  let res = await request("/login/refresh")
  //  console.log(res)
  },

  //获取用户播放记录
  async userRecentPlayList(userid){
    let index = 0;
    let globList = [];
    let res = await request('/user/record',{uid:userid,type:1})
    let userRecentPlayList = res.weekData.splice(0,15).map(item =>{
      item.id = index++;
      return item;
    })
    // console.log(userRecentPlayList)

    userRecentPlayList.forEach((item,index) => {
      let obj = {}
      obj.name = item.song.al.name;
      obj.artists= item.song.ar;
      obj.id = item.song.id
      globList.push(obj)
    });
    // console.log(globList)

    this.setData({
      userRecentPlayList,
      globList
    })

  },
 
    // 跳转至songDetail页面
    // toSongDetail(event){
    //   let that = this;
    //   // console.log(event.currentTarget.dataset)
    //   let {song, index} = event.currentTarget.dataset;
    //   this.setData({
    //     index
    //   })
    //   // 路由跳转传参： query参数
    //   // console.log(song.song.id)
    //   wx.navigateTo({
    //     // 不能直接将song对象作为参数传递，长度过长，会被自动截取掉
    //     // url: '/pages/songDetail/songDetail?songPackage=' + JSON.stringify(songPackage)
    //     url: `/pages/songPackage/pages/songDetail/songDetail?type=${this.data.type}&musicId=` + song.song.id,
    //     success:function(){
    //       console.log("成功调用")
    //       appInstance.globalData.playList = that.data.globList;
    //       appInstance.globalData.currentIndex = index;
    //       // console.log(appInstance.globalData.playList)
    //     }
    //   })
    // },

    toSongDetail(event){
    
      let that = this;
      let globList=[];
      let index
      if(event.currentTarget.dataset.index){
         index = event.currentTarget.dataset.index;
      }else{
        index = 0
      }
      
      let {likemusics} =this.data
      let songlist = likemusics
      this.setData({
        index,
        type:`personalType`
      })
       console.log(songlist)
      songlist.forEach((item,index) => {
        console.log(item.ar.name)
          let obj = {}
          obj.name = item.name;
          obj.artists= item.ar.name;
          obj.id = item.id
          globList.push(obj)
        });
        // console.log(globList)
    
        this.setData({
          globList
        })
    
        
        appInstance.globalData.playList = that.data.globList;
        appInstance.globalData.currentIndex = index;
        console.log(index)
        // console.log(songlist[index].id)
      // 路由跳转传参： query参数
      wx.navigateTo({
        // 不能直接将song对象作为参数传递，长度过长，会被自动截取掉
        // url: '/pages/songDetail/songDetail?songPackage=' + JSON.stringify(songPackage)
        url: `/pages/songPackage/pages/playmusic/playmusic?type=${this.data.type}&musicId=` + songlist[index].id,
        // success:function(){
  
        // }
      },
  
      )
    },


  handleTouchStart(event){
    this.setData({
     
      coveTransition:''
   })
    // console.log(event)
    
    startY = event.touches[0].clientY;
    
  },
  handleTouchEnd(){
    this.setData({
       coverTransform:'translateY(0)',
       coveTransition:'transform 1s linear'
    })
  },
   bindButtonTap() {
    const that = this
    if(wx.getStorageSync('userInfo')){
      wx.chooseImage({
        sourceType: ['album', 'camera'],
        sizeType:["compressed","original"],
        // camera: ['front', 'back'],
         success(res) {
          let src =  res.tempFilePaths[0]
          if(wx.getStorageSync('src')){wx.removeStorageSync('src')}
          wx.setStorageSync('src',src)
          that.setData({
            src
          })
          // console.log(res)
          wx.getImageInfo({
            src,
            success (resInfo) {
              console.log(resInfo.width)
              that.updataImg(res , resInfo.width)
            }
          })
          
          
        }
      })
    }else{
      wx.navigateTo({
        url: '../login/login',
      })
    }
    
  },
  //跟新头像
  updataImg(src,width){
    let url = src.tempFilePaths[0] 
    // let width = this.imgInfo(url)
    // console.log("width:",width)
    wx.uploadFile({
      url:`http://175.178.28.181:4000/avatar/upload?imgSize=${width}`,
      header:{
        cookie: wx.getStorageSync('cookies')?wx.getStorageSync('cookies').find(item => item.indexOf('MUSIC_U') !== -1):'',
        "Conten-tType": 'multipart/form-data',
      },
      // formData,
      name:"imgFile",
      data:{
        //  imgSize:src.tempFiles[0].size,
      },
      filePath:url,
      success:(suss)=>{
        console.log(suss)
      }
    })
    // console.log(src)
    // let result = await postRequest('/avatar/upload',{src})
    // console.log(result)
  },
   
 
  
  toRecent(){
    let uid = this.data.userInfo.userId;
    wx.navigateTo({
      url: `/pages/recent/recent?uid=${uid}`,

    })
  },
  toLogin(){
    // console.log("user",this.data.userInfo)
    let userInfo = wx.getStorageSync('userInfo');
    if( userInfo){return}else{
      wx.navigateTo({
        url: '../login/login',
      })
    }
    // if(this.data.userInfo){
    //   wx.navigateTo({
    //     url: '../login/login',
    //   })
    // }
    // else{

    // }

  },


  handleTouchMove(event){
    // console.log(event)
    // event.stopPropagation()
    moveY = event.touches[0].clientY;
    moveDistance = moveY - startY ;
    if(moveDistance < 0) return
    else if(moveDistance > 100){
      moveDistance = 100
    }
    this.setData({
      coverTransform:`translateY(${moveDistance}rpx)`
    })
    // console.log(moveY)
    // console.log(moveDistance)
  },
 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})